﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM
{
    public partial class WSCManagement_VSM : System.Web.UI.Page
    {
        private int _rowCount = 0;
        private int _checkRow = 0;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (!IsPostBack)
            {
                ////authorization
                //if (Session[Utils.AppConstants.ManagerUser].ToString() == "")
                //{ //is manager
                //    btn_Submit.Text = "Submit To VSM";
                //}
                //else {//not a manager 
                //    btn_Submit.Text = "Submit To Header";
                //    grdItem.Columns[10].Visible = false;
                //}

                
                DateTime firstDate = DateTime.Today.AddDays(1 - DateTime.Today.Day);
                DateTime firstDateNextMonth = firstDate.AddMonths(1);
                DateTime lastDate = firstDateNextMonth.AddDays(-1);

                txtFromDate.Text = firstDate.ToString("dd/MM/yyyy");
                txtToDate.Text = lastDate.ToString("dd/MM/yyyy");
                createStatusDll();
                createStatusDealer();
            }
        }

        private void createStatusDll()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Code");
            dt.Columns.Add("Name");
            dt.Rows.Add("(4,5,6)", "All");
            dt.Rows.Add("(4)", "Waiting");
            dt.Rows.Add("(5)", "Approved");
            dt.Rows.Add("(6)", "Rejected");

            ddlStatus.DataSource = dt;
            ddlStatus.DataTextField = "Name";
            ddlStatus.DataValueField = "Code";
            ddlStatus.DataBind();
        }

        private void createStatusDealer()
        {
            string sql = "select '-1' CardCode, 'All' CardName ";
            sql += " union all ";
            sql += " select CardCode, CardName from OCRD where CardType = 'C' and U_WareHouse is not null ";
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddl_Dealer.DataSource = ds.Tables[0];
                ddl_Dealer.DataTextField = "CardName";
                ddl_Dealer.DataValueField = "CardCode";
                ddl_Dealer.DataBind();
            }
        }
       
       
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dt = Session["ItemTable"] as DataTable;
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                this.grdItem.DataSource = Session["ItemTable"];
                this.grdItem.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                if (Session["ChosenItem"] != null)
                {
                    Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                    Label code = (Label)e.Row.FindControl("lblItemCode");
                    try
                    {
                        if (code != null && dicItem[code.Text.Trim()].Length > 0)
                        {
                            CheckBox checkBox = (CheckBox)e.Row.FindControl("chkChild");
                            if (checkBox != null)
                            {
                                checkBox.Checked = true;
                                _checkRow++;
                                if (_checkRow == _rowCount)
                                {
                                    //Check All
                                    GridViewRow headerRow = this.grdItem.HeaderRow;
                                    ((CheckBox)headerRow.FindControl("chkheader")).Checked = true;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //
                    }
                }
            }
        }

       

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindBP(DataTable tb)
        {
            Session["ItemTable"] = tb;
            this.grdItem.DataSource = tb;
            this.grdItem.DataBind();
        }

        protected void btn_Filter_Click(object sender, EventArgs e)
        {
            LoadDataFilter();
        }

        private void LoadDataFilter()
        {
            string sql = "select ROW_NUMBER() OVER(ORDER BY A.GeneralID DESC) AS No, * from ( ";
            sql += " select gs.GeneralID, gs.ServiceDate, 'A' WSCType, ws.DealerCode, ws.DealerName, ";
            sql += " ws.SeqNo, ws.VIN, ws.CustomerName, ws.FailureDate, ws.Model, ws.EngineNumber,    ";
            sql += " ConditionCode, ws.RegistrationNum, gs.Status, ";
            sql += " case when gs.Status = 4 then 'Waiting' when gs.Status = 5 then 'Approved'  ";
            sql += " when gs.Status = 6 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";
            sql += " from U_GeneralService gs     ";
            sql += " left join U_WSC ws on gs.GeneralID = ws.GeneralID where gs.JobKind = '004' AND WSCType is null   ";
            sql += " and gs.Status in " + ddlStatus.SelectedValue;
            sql += " AND gs.ServiceDate BETWEEN '" + VSM.Utils.AppConstants.ConvertToDate(txtFromDate.Text) + "' AND '" + VSM.Utils.AppConstants.ConvertToDate(txtToDate.Text) + "'";
            if (ddl_Dealer.SelectedValue != "-1")
                sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";
            sql += " union all  ";

            sql += " select GeneralID, ServiceDate, WSCType, DealerCode, DealerName, ";
            sql += " SeqNo, VIN, CustomerName, FailureDate, Model, EngineNumber, ";
            sql += " ConditionCode,  RegistrationNum, Status, StatusName, VSMStatus  from ( ";
            sql += " select row_number() over(partition by gs.GeneralID order by gs.GeneralID desc) as roworder, gs.GeneralID, gs.ServiceDate, WSCType, gs.DealerCode, gs.DealerName, ";
            sql += " gs.SeqNo, det.VIN, ''CustomerName, null FailureDate, '' Model, ''EngineNumber, ";
            sql += " ''ConditionCode, '' RegistrationNum, gs.Status,   ";
            sql += " case when gs.Status = 4 then 'Waiting' when gs.Status = 5 then 'Approved'  ";
            sql += " when gs.Status = 6 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";
            sql += " from U_GeneralService gs join U_WSCBDetail det on det.GeneralID = gs.GeneralID ";
            sql += " where gs.JobKind = '004' AND WSCType = 'B' ";
            sql += " AND gs.Status in " + ddlStatus.SelectedValue;
            sql += " AND gs.ServiceDate BETWEEN '" + VSM.Utils.AppConstants.ConvertToDate(txtFromDate.Text) + "' AND '" + VSM.Utils.AppConstants.ConvertToDate(txtToDate.Text) + "'";
            if (ddl_Dealer.SelectedValue != "-1")
                sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";
            sql += " ) tmp where roworder = 1 ";
            sql += " )A order by DealerCode ";

            //string sql = "select ROW_NUMBER() OVER(ORDER BY A.GeneralID DESC) AS No, * from ( ";
            //sql += " select gs.GeneralID, gs.ServiceDate, 'A' WSCType, ws.DealerCode, ws.DealerName, ";
            //sql += " ws.SeqNo, ws.VIN, ws.CustomerName, ws.FailureDate, ws.Model, ws.EngineNumber,   ";
            //sql += " ConditionCode, ws.RegistrationNum, gs.Status,   ";
            //sql += " case when gs.Status = 4 then 'Waiting' when gs.Status = 5 then 'Approved'  ";
            //sql += " when gs.Status = 6 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";

            //sql += " from U_GeneralService gs   ";
            //sql += " left join U_WSC ws on gs.GeneralID = ws.GeneralID where gs.JobKind = '004' AND WSCType is null ";
            //if (ddl_Dealer.SelectedValue != "-1")
            //    sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";

            //sql += " union all ";

            //sql += " select gs.GeneralID, gs.ServiceDate, 'B' WSCType, gs.DealerCode, gs.DealerName, ";
            //sql += " gs.SeqNo, '' as VIN, '' as CustomerName, '' as FailureDate, '' as Model, '' as EngineNumber, ";
            //sql += " '' as ConditionCode, '' as RegistrationNum, gs.Status, ";
            //sql += " case when gs.Status = 4 then 'Waiting' when  gs.Status = 5 then 'Approved'  ";
            //sql += " when gs.Status = 6 then 'Rejected' else '' end as StatusName, gs.VSMStatus ";

            //sql += " from U_GeneralService gs ";
            //sql += " where gs.JobKind = '004' AND WSCType = 'B' ";
            //if (ddl_Dealer.SelectedValue != "-1")
            //    sql += " AND gs.DealerCode = '" + ddl_Dealer.SelectedValue + "' ";


            //sql += " ) A where 1=1 AND A.Status in " + ddlStatus.SelectedValue;

            //if (ddlStatus.SelectedValue != "-1")
            //{            sql += " case when isnull(gs.VSMStatus, 0) = 1 AND gs.Status = 1 then 'Seen' else '' end as VSMStatusName  ";
            //    sql += " AND A.Status = " + ddlStatus.SelectedValue;
            //}             sql += " case when isnull(gs.VSMStatus, 0) = 1 AND gs.Status = 1 then 'Seen' else '' end as VSMStatusName  ";

            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            grdItem.DataSource = ds.Tables[0];
            grdItem.DataBind();
            Session["DetailWSC"] = ds.Tables[0];
        }

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            //Dictionary<string, string> dicItem = new Dictionary<string, string>();
            for (int i = 0; i < this.grdItem.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grdItem.Rows[i].FindControl("chkChild");

                if (checkBox != null)
                {
                    if (checkBox.Checked)
                    {
                        Label gID = (Label)this.grdItem.Rows[i].FindControl("lbGeneralID");

                        Services sv = new Services();
                        sv.ExecuteQuery("DEALER", "UPDATE U_GeneralService SET Status = 5 WHERE GeneralID = " + gID.Text);
                    }
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete,');", true);
            LoadDataFilter();
        }

        protected void btn_Reject_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grdItem.Rows.Count; i++)
            {
                CheckBox checkBox = (CheckBox)this.grdItem.Rows[i].FindControl("chkChild");

                if (checkBox != null)
                {
                    if (checkBox.Checked)
                    {
                        Label gID = (Label)this.grdItem.Rows[i].FindControl("lbGeneralID");

                        Services sv = new Services();
                        sv.ExecuteQuery("DEALER", "UPDATE U_GeneralService SET Status = 6 WHERE GeneralID = " + gID.Text);
                    }
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Update Complete,');", true);
            LoadDataFilter();
        }

        protected void btn_CheckValidWSC_Click(object sender, EventArgs e)
        {
            DataTable data = (DataTable)Session["DetailWSC"];
            if (data != null)
            {
                string msg = "";
                foreach (DataRow dr in data.Rows)
                {
                    string type = dr["WSCType"].ToString();
                    if (type == "A")
                    {
                        string VIN = dr["VIN"].ToString();
                        string gID = dr["GeneralID"].ToString();
                        string errMsg = checkValidWSCA(gID, VIN) + "\n";
                        if (errMsg == "")
                            msg += "[" + dr["GeneralID"].ToString() + "]" + VIN + ": OK \n";
                        else
                            msg += "[" + dr["GeneralID"].ToString() + "]" + VIN + " " + errMsg + "\n";
                    }
                    else { //WSC B
                        string gID = dr["GeneralID"].ToString();
                        string errMsg = checkValidWSCB(gID);
                        if (errMsg == "")
                            msg += "[" + dr["GeneralID"].ToString() + "]" + ": OK \n";
                        else
                            msg += "[" + dr["GeneralID"].ToString() + "]" + " " + errMsg + "\n";
                    }
                }
                txt_CheckResult.Text = msg;
            }
            else
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Please filter data first.');", true);
        }

        private string checkValidWSCB(string GeneralID) {
            string msg = "";
            string sql = "select * from U_WSCBDetail where Status = 0 and GeneralID = " + GeneralID;
            Services svc = new Services();
            DataTable tb = svc.ExecuteQuery("DEALER", sql).Tables[0];
            foreach (DataRow dr in tb.Rows) {
                string VIN = dr["VIN"].ToString();
                string err = checkVIN(VIN);
                if (err != "") {
                    msg += VIN + " - " + err + "\n";
                }
            }
            return msg;
        }

        private string checkValidWSCA(string GeneralID, string VIN)
        {
            string msg = "";
            string sqlInfo = " SELECT gs.GeneralID, wsc.InvoiceDate, wsc.A, wsc.B, wsc.C, wsc.FailureDate, wsc.ConditionCode, KD, ";
            sqlInfo += " gs.ServiceDate, lb.PositionCode ";
            sqlInfo += " FROM U_GeneralService gs join U_WSC wsc on gs.GeneralID = wsc.GeneralID ";
            sqlInfo += " left join U_GeneralServiceLabour lb on lb.GeneralID = gs.GeneralID ";
            sqlInfo += " WHERE gs.GeneralID=" + GeneralID;
            Services sv = new Services();
            DataTable dt = sv.ExecuteQuery("DEALER", sqlInfo).Tables[0];
            string KD = dt.Rows[0]["KD"].ToString();
            DateTime failureDate = DateTime.Parse(dt.Rows[0]["FailureDate"].ToString());
            DateTime serviceDate = DateTime.Parse(dt.Rows[0]["ServiceDate"].ToString());
            DateTime soldDate = DateTime.Parse(dt.Rows[0]["InvoiceDate"].ToString());
            TimeSpan dateiff = serviceDate.Subtract(failureDate);

            msg = checkVIN(VIN);
            if (dateiff.TotalDays > 15)
            {
                msg += "Service Date and Failure Date are not valid [Exceed " + dateiff.TotalDays + " days]. ";
            }

            if (KD == "1")//da ban
                if (failureDate < soldDate)
                    msg += "The Sold date is greater than the Failure date. ";

            if (dt.Rows[0]["ConditionCode"].ToString() != dt.Rows[0]["PositionCode"].ToString())
                msg += "The Condition Code is different from the Posiotion Code. ";

            msg += checkConditionCode(dt.Rows[0]["ConditionCode"].ToString());

            msg += checkABCCode(dt.Rows[0]["A"].ToString(), dt.Rows[0]["B"].ToString(), dt.Rows[0]["C"].ToString());

            //sqlInfo = ""
            //1. Check VIN in Sales Data
            //2. Failure Date and Service Date
            //3. Failure Date and Sold Date
            //4. Check HB if in FRT
            //5. A, B, C code
            //6. LA same as HB
            return msg;
        }

        private string checkVIN(string VIN) {
            string msg = "";
            string sqlCheckVIN = "SELECT rn.ItemCode, rn.DistNumber, rq.WhsCode, rq.Quantity, rn.inDate ";
            sqlCheckVIN += " FROM OSRN rn with(nolock) ";
            sqlCheckVIN += " LEFT JOIN OSRQ rq with(nolock) ON rn.ItemCode = rq.ItemCode AND rn.SysNumber = rq.SysNumber ";
            sqlCheckVIN += " WHERE DistNumber = '" + VIN + "'";
            Services sv = new Services();
            DataTable dtCheckVIN = sv.ExecuteQuery("VSM", sqlCheckVIN).Tables[0];
            if (dtCheckVIN.Rows.Count == 0) {
                msg = "VIN not exist. ";
            }
            return msg;
        }

        private string checkABCCode(string strA, string strB, string strC) {
            string msg = "";
            string sqlA = "select * from U_RefCode where Type = 'A' and Code = '" + strA + "'";
            Services sv = new Services();
            if (sv.ExecuteQuery("VSM", sqlA).Tables[0].Rows.Count == 0)
                msg += "The Condition Code [A]: " + strA + " is not valid. ";

            string sqlB = "select * from U_RefCode where Type = 'B' and Code = '" + strB + "'";
            if (sv.ExecuteQuery("VSM", sqlB).Tables[0].Rows.Count == 0)
                msg += "The Condition Code [B]: " + strB + " is not valid. ";

            string sqlC = "select * from U_RefCode where Type = 'C' and Code = '" + strC + "'";
            if (sv.ExecuteQuery("VSM", sqlC).Tables[0].Rows.Count == 0)
                msg += "The Condition Code [C]: " + strC + " is not valid. ";
            return msg;
        }

        private string checkConditionCode(string condCode) {
            string msg = "";
            Services sv = new Services();
            string sql = "select * from U_FRT where FRTCode = '" + condCode + "'";
            if (sv.ExecuteQuery("VSM", sql).Tables[0].Rows.Count == 0)
                msg = "The Condition Code [" + condCode + "] is not valid. ";
            return msg;
        }
    }
}
